package de.slothsoft.stube;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.google.android.gms.ads.AdView;

import de.slothsoft.stube.util.AdvertizingUtil;
import de.slothsoft.stube.util.StubeUtil;

public class MapActivity extends Activity {

    private AdView adView;

    private WebView webView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

	setContentView(R.layout.activity_map);
	setupWebView();

	this.adView = AdvertizingUtil.addAd(this, (LinearLayout) findViewById(R.id.layout));
    }

    @Override
    public void onPause() {
	this.adView.pause();
	super.onPause();
    }

    @Override
    public void onResume() {
	super.onResume();
	this.adView.resume();
    }

    @Override
    public void onDestroy() {
	this.adView.destroy();
	super.onDestroy();
    }

    private Location findLastLocation() {
	LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	if (locationManager == null) return null;
	Criteria criteria = new Criteria();
	criteria.setAccuracy(Criteria.ACCURACY_FINE);
	String provider = locationManager.getBestProvider(criteria, true);
	return locationManager.getLastKnownLocation(provider);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void setupWebView() {
	this.webView = (WebView) findViewById(R.id.webview);
	this.webView.getSettings().setJavaScriptEnabled(true);
	this.webView.setWebViewClient(new WebViewClient() {
	    @Override
	    public void onPageFinished(WebView view, String url) {
		onMapLoaded();
	    }

	    @Override
	    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
		getWebView().loadUrl("file:///android_asset/404.htm");
	    }

	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
		if (url.startsWith("local:")) {
		    if (url.endsWith("refresh")) {
			getWebView().loadUrl(getMapUrl());
		    } else if (url.endsWith("exit")) {
			finish();
		    }
		    return true;
		}
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		startActivity(intent);
		return true;
	    }

	});
	this.webView.loadUrl(getMapUrl());
    }

    protected void onMapLoaded() {
	centerOn(findLastLocation());
    }

    protected String getMapUrl() {
	return StubeUtil.getMapUrl(getResources().getString(R.string.federalStateId));
    }

    public void centerOn(String address) {
	final String centerURL = "javascript:centerAtAddress('" + encode(address) + "')";
	Log.i("slothsoft", "JS executed: " + centerURL);
	this.webView.loadUrl(centerURL);
    }

    public void centerOn(Location location) {
	if (location != null) {
	    centerOn(location.getLatitude(), location.getLongitude());
	}
    }

    public void centerOn(double latitude, double longitude) {
	final String centerURL = "javascript:centerAtCoordinates(" + latitude + "," + longitude + ")";
	Log.i("slothsoft", "JS executed: " + centerURL);
	this.webView.loadUrl(centerURL);
    }

    private String encode(String string) {
	return string == null ? "" : string.replace("'", "\\'");
    }

    protected WebView getWebView() {
	return this.webView;
    }

}